package com.srwl.mytx.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.WithdrawRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Transfer;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.RPTitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WithDrawRecordActivity extends BaseActivity {
    private static final String TAG = "WithDrawRecordActivity";

    @BindView(R.id.rl_recharge_record)
    RecyclerView rv_rechargeRecord;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    private List<Transfer> transferList = new ArrayList<>();
    private WithdrawRecordAdapter adapter;
    private boolean hasNextPage;
    private int size = 20;
    private int page = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_record);
        ButterKnife.bind(this);
        LinearLayoutManager manager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        rv_rechargeRecord.setLayoutManager(manager);
        adapter = new WithdrawRecordAdapter(this, transferList);
        rv_rechargeRecord.setAdapter(adapter);
        if (isTempUser()) {
            adapter.showNoDataView();
        } else {
            loadData(true);
        }
        initRefreshLayout();
        initTitleBar();
    }

    private void initTitleBar() {
        RPTitleBar mTitleBar = findViewById(R.id.title_bar);
        mTitleBar.setSubTitleVisibility(View.GONE);
        mTitleBar.setRightImageResource(R.drawable.tx_right_menu_yellow);
        mTitleBar.setRightImageLayoutVisibility(View.VISIBLE);
        mTitleBar.setTitle("提现记录");
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    //必须重新，不然状态栏字体是黑色，，
    protected void setStatusDark() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.rp_top_red_color));
    }


    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> info = new HashMap<>();
        //分页信息，从1页开始，每页20条
        info.put("size", size);
        info.put("page", page);

        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(AliService.class)
                .getTransferRecord(info)
                .enqueue(new Callback<CommonResult>() {

                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取充值记录出错 " + response.message());
                            adapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "获取充值记录出错 " + result.getMsg());
                            adapter.showErrorView();
                            if (result.getStatus() == Constant.TOKEN_INVALID) {
                                showToast(getString(R.string.login_expire));
                            }
                            return;
                        }

                        Log.d(TAG, "获取充值记录完成 " + page);
                        JSONObject pageInfo = (JSONObject) result.getData();
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.setFooterView(new NodataFooter(WithDrawRecordActivity.this));
                        }
                        List<Transfer> transfers = pageInfo.getJSONArray("list").toJavaList(Transfer.class);

                        // List<Recharge> rechargeList = JSONObject.parseArray(result.getData().toString(), Recharge.class);
                        if (transfers.size() != 0) {
                            transferList.addAll(transfers);
                            adapter.showNormalView();
                            page++;
                        } else if (page == 1) {
                            adapter.showNoDataView();
                        }


                     /*   recharges.addAll(rechargeList);
                        adapter.notifyDataSetChanged();
                        page++;*/

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        adapter.showErrorView();
                        Log.e(TAG, "获取充值记录出错 " + t.getMessage());

                    }
                });


    }

    void initRefreshLayout() {
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setOnLoadMoreScrollCallback(new SmoothRefreshLayout.OnLoadMoreScrollCallback() {
            @Override
            public void onScroll(View content, float delta) {

                rv_rechargeRecord.scrollBy(0, (int) delta);
            }
        });
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {


            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

    /**
     * 判断是否是游客
     *
     * @return
     */
    private boolean isTempUser() {
        if (UserProfileManager.getInstance().getLoginUserInfo().getType() == Constant.USER_TYPE_TEMP) {
            return true;
        }
        return false;
    }


}
